package model.daos;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import model.db.DataBase;
import model.dtos.Team;

public class TeamDao implements GenericDao<Team>
{

	@Override
	public void save(Team dt)
	{
		DataBase.getSeason().getTeams().add(dt);
	}

	@Override
	public Team findById(String id)
	{
		Team team = null;
		
		for (Team t : DataBase.getSeason().getTeams())
		{
			if (t.getCode().equals(id))
			{
				team = t;
				break;
			}
		}
		
		return team;
	}

	@Override
	public List<Team> findAll()
	{
		return DataBase.getSeason().getTeams();
	}

	@Override
	public void deleteById(String id)
	{
		Iterator<Team> it = DataBase.getSeason().getTeams().iterator();
		
		while (it.hasNext())
		{
			if (it.next().getCode().equals(id))
			{
				it.remove();
				break;
			}
		}
	}

	@Override
	public void deleteAll()
	{
		DataBase.getSeason().getTeams().clear();
	}
	
	public void loadTeamsFromFile(File file) throws IOException, ParseException
	{
		BufferedReader bf = new BufferedReader(new FileReader(file));
		
		String line = null;
		while ((line = bf.readLine()) != null)
		{
			StringTokenizer tok = new StringTokenizer(line, ";");
			DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
						
			DataBase.getSeason().getTeams().add(new Team(tok.nextToken(), tok.nextToken(), tok.nextToken(), tok.nextToken(), df.parse(tok.nextToken())));
		}
	}
	
	public Team mostWinner()
	{
		List<Team> teams = new ArrayList<Team>(this.findAll());
		
		Collections.sort(teams, new Comparator<Team>() {
			
			public int compare(Team t1, Team t2)
			{
				return t1.getWonGames() > t2.getWonGames() ? -1 : (t1.getWonGames() == t2.getWonGames() ? (t1.getLostGames() < t2.getLostGames() ? -1 : (t1.getWonGames() == t2.getWonGames() ? 0 : 1)) : 1);
			}
		});
		
		return teams.get(0);
	}
	
	public Team mostLoser()
	{
		List<Team> teams = new ArrayList<Team>(this.findAll());
		
		Collections.sort(teams, new Comparator<Team>() {
			
			public int compare(Team t1, Team t2)
			{
				return t1.getWonGames() > t2.getWonGames() ? -1 : (t1.getWonGames() == t2.getWonGames() ? (t1.getLostGames() < t2.getLostGames() ? -1 : (t1.getWonGames() == t2.getWonGames() ? 0 : 1)) : 1);
			}
		});
		
		return teams.get(teams.size() - 1);
	}
}
